<template>
  <div class="vaccine-plan">
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
      <!-- 疫苗列表 -->
      <el-form-item label="疫苗列表" prop="vaccineList">
        <div class="vaccine-list">
          <div
            v-for="(vaccine, index) in vaccineList"
            :key="vaccine.id"
            class="vaccine-item"
          >
            <!-- 疫苗头部信息 -->
            <div class="vaccine-header">
              <div class="vaccine-title">
                <span class="vaccine-name">{{ vaccine.vaccineName }}</span>
                <span class="dose-info"
                  >第 {{ vaccine.currentDose }} 剂共
                  {{ vaccine.totalDoses }} 剂</span
                >
              </div>
              <el-button
                v-if="!isViewMode"
                type="danger"
                link
                size="small"
                @click="handleDeleteVaccine(index)"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>

            <!-- 疫苗详细信息 -->
            <div class="vaccine-details">
              <!-- 疫苗名称 -->
              <div class="form-row">
                <label class="form-label">疫苗名称</label>
                <div class="form-content">
                  <el-select
                    v-model="vaccine.vaccineType"
                    placeholder="请选择疫苗名称"
                    style="width: 100%"
                    :disabled="isViewMode"
                    @change="handleVaccineNameChange(vaccine)"
                  >
                    <el-option
                      v-for="item in vaccineOptions"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                    <el-option
                      v-if="vaccineOptions.length === 0"
                      label="暂无疫苗选项"
                      value=""
                      disabled
                    />
                  </el-select>
                </div>
              </div>

              <!-- 剂次信息 -->
              <div class="form-row">
                <label class="form-label">剂次</label>
                <div class="form-content">
                  <el-input-number
                    v-model="vaccine.currentDose"
                    :min="1"
                    :max="vaccine.totalDoses"
                    size="small"
                    style="width: 80px"
                    :disabled="isViewMode"
                  />
                  <span class="dose-separator">/</span>
                  <el-input-number
                    v-model="vaccine.totalDoses"
                    :min="1"
                    :max="10"
                    size="small"
                    style="width: 80px"
                    :disabled="isViewMode"
                  />
                </div>
              </div>

              <!-- 本次接种日期 -->
              <div class="form-row">
                <label class="form-label">本次接种日期</label>
                <div class="form-content">
                  <el-date-picker
                    v-model="vaccine.vaccinationDate"
                    type="date"
                    placeholder="选择接种日期"
                    style="width: 100%"
                    value-format="x"
                    :disabled="isViewMode"
                  />
                </div>
              </div>

              <!-- 接种时间窗 -->
              <div class="form-row">
                <label class="form-label">接种时间窗</label>
                <div class="form-content">
                  <el-radio-group
                    v-model="vaccine.timeWindowType"
                    :disabled="isViewMode"
                  >
                    <el-radio :label="'asap'">
                      <span class="radio-text"
                        >尽快接种 (1个月内，即从创建/编辑后1个月内)</span
                      >
                    </el-radio>
                    <el-radio :label="'suggested'">
                      <span class="radio-text">建议时段</span>
                      <el-date-picker
                        v-if="vaccine.timeWindowType === 'suggested'"
                        v-model="vaccine.timeWindowRange"
                        type="daterange"
                        range-separator="~"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        style="width: 230px; margin-left: 8px"
                        value-format="x"
                        :disabled="isViewMode"
                      />
                    </el-radio>
                  </el-radio-group>
                </div>
              </div>

              <!-- 禁忌注意事项 -->
              <div class="form-row">
                <label class="form-label">禁忌注意事项</label>
                <div class="form-content">
                  <el-radio-group
                    v-model="vaccine.contraindicationType"
                    :disabled="isViewMode"
                  >
                    <el-radio :label="'none'">
                      <span class="radio-text">无禁忌</span>
                    </el-radio>
                    <el-radio :label="'custom'">
                      <span class="radio-text">需禁忌</span>
                      <el-input
                        v-if="vaccine.contraindicationType === 'custom'"
                        v-model="vaccine.contraindicationText"
                        type="textarea"
                        :rows="2"
                        placeholder="请输入禁忌注意事项，如：不能喝酒、不能吃辛辣食品"
                        style="width: 300px; margin-left: 8px"
                        :disabled="isViewMode"
                      />
                    </el-radio>
                  </el-radio-group>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-form-item>
    </el-form>

    <!-- 添加疫苗按钮 -->
    <div v-if="!isViewMode" class="add-button">
      <el-button type="primary" plain @click="handleAddVaccine">
        <el-icon><Plus /></el-icon>
        添加
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { Delete, Plus } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { computed, defineEmits, defineProps, onMounted, ref, watch } from "vue";

import type {
  VaccinationTaskParams,
  VaccinationUpdateFrom
} from "@/api/follow";
import { followApi } from "@/api/follow";
import { userKey } from "@/utils/auth";
import { storageLocal } from "@pureadmin/utils";

// 定义疫苗项目接口（用于前端展示）
interface VaccineItem {
  id: number;
  vaccineName: string;
  vaccineType: number;
  currentDose: number;
  totalDoses: number;
  vaccinationDate: string;
  timeWindowType: "asap" | "suggested";
  timeWindowRange: [string, string] | null;
  contraindicationType: "none" | "custom";
  contraindicationText: string;
}
const vaccineOptions = ref<any[]>([]);
const props = defineProps<{
  userId: number;
  planId?: string | string[];
  mode?: "create" | "edit" | "view"; // 组件模式：创建、编辑、查看
}>();
onMounted(() => {
  getFollowUpPlanCondition();
});

const getFollowUpPlanCondition = async () => {
  const response = await followApi.getFollowUpPlanCondition({
    userId: (storageLocal().getItem(userKey) as any).userId
  });
  if (response?.data) {
    vaccineOptions.value = response.data.vaccinationType;
  }
};
// 默认模式为创建
const defaultMode = computed(() => props.mode || "create");

// 计算是否为查看模式
const isViewMode = computed(() => defaultMode.value === "view");

// 计算是否为编辑模式
const isEditMode = computed(() => defaultMode.value === "edit");

// 计算是否为创建模式
const isCreateMode = computed(() => defaultMode.value === "create");

const emit = defineEmits(["update:modelValue", "submit"]);

// 表单引用
const formRef = ref();

// 疫苗列表
const vaccineList = ref<VaccineItem[]>([]);

// 表单数据
const formData = ref<VaccinationTaskParams>({
  userId: props.userId,
  vaccineType: null, // 初始化为0，表示未选择
  currentDoseNumber: 1,
  totalDoses: 3,
  vaccinationDate: "",
  recommendedDate: "",
  asap: 2, // 默认尽快接种
  windowStartDate: "",
  windowEndDate: "",
  precautions: ""
});

// 计算属性：验证疫苗列表
const validateVaccineList = computed(() => {
  if (vaccineList.value.length === 0) {
    return false;
  }

  return vaccineList.value.every(vaccine => {
    return (
      vaccine.vaccineType > 0 && // 确保选择了疫苗类型
      vaccine.vaccinationDate &&
      vaccine.timeWindowType &&
      vaccine.contraindicationType &&
      (vaccine.contraindicationType !== "custom" ||
        vaccine.contraindicationText.trim())
    );
  });
});

// 表单验证规则
const rules = {
  vaccineList: [
    {
      required: true,
      validator: (rule: any, value: any, callback: any) => {
        if (vaccineList.value.length === 0) {
          callback(new Error("请至少添加一个疫苗计划"));
        } else if (!validateVaccineList.value) {
          callback(new Error("请完善疫苗计划信息"));
        } else {
          callback();
        }
      },
      trigger: "change"
    }
  ]
};

// 生成新的疫苗ID
const generateVaccineId = () => {
  const maxId = Math.max(...vaccineList.value.map(item => item.id), 0);
  return maxId + 1;
};

// 添加疫苗
const handleAddVaccine = () => {
  console.log("添加疫苗计划 - 开始创建新的疫苗项目");

  const newVaccine: VaccineItem = {
    id: generateVaccineId(),
    vaccineName: "",
    vaccineType: null, // 初始化为0，表示未选择
    currentDose: 1,
    totalDoses: 3,
    vaccinationDate: "",
    timeWindowType: "asap",
    timeWindowRange: null,
    contraindicationType: "none",
    contraindicationText: ""
  };

  vaccineList.value.push(newVaccine);
  console.log("添加疫苗计划 - 新疫苗项目已创建", newVaccine);

  updateFormData();
};

// 删除疫苗
const handleDeleteVaccine = (index: number) => {
  console.log("删除疫苗计划 - 准备删除索引为", index, "的疫苗项目");

  const vaccine = vaccineList.value[index];
  console.log("删除疫苗计划 - 要删除的疫苗信息", vaccine);

  vaccineList.value.splice(index, 1);
  console.log(
    "删除疫苗计划 - 疫苗项目已删除，当前列表长度",
    vaccineList.value.length
  );

  updateFormData();
};

// 处理疫苗名称变化
const handleVaccineNameChange = (vaccine: VaccineItem) => {
  console.log("疫苗名称变化 - 疫苗信息", vaccine);
  // 根据选择的疫苗类型ID获取疫苗名称
  const selectedVaccine = vaccineOptions.value.find(
    item => item.id === vaccine.vaccineType
  );
  if (selectedVaccine) {
    vaccine.vaccineName = selectedVaccine.name;
    console.log("疫苗名称变化 - 已更新疫苗名称为:", vaccine.vaccineName);
  }
  updateFormData();
};

// 更新表单数据
const updateFormData = () => {
  if (vaccineList.value.length > 0) {
    const vaccine = vaccineList.value[0]; // 取第一个疫苗项目

    formData.value = {
      userId: props.userId,
      vaccineType: vaccine.vaccineType,
      currentDoseNumber: vaccine.currentDose,
      totalDoses: vaccine.totalDoses,
      vaccinationDate: vaccine.vaccinationDate,
      recommendedDate: vaccine.vaccinationDate, // 推荐日期使用接种日期
      asap: vaccine.timeWindowType === "asap" ? 2 : 1,
      windowStartDate:
        vaccine.timeWindowType === "suggested" && vaccine.timeWindowRange
          ? vaccine.timeWindowRange[0]
          : "",
      windowEndDate:
        vaccine.timeWindowType === "suggested" && vaccine.timeWindowRange
          ? vaccine.timeWindowRange[1]
          : "",
      precautions:
        vaccine.contraindicationType === "custom"
          ? vaccine.contraindicationText
          : ""
    };
  }

  console.log("更新表单数据 - 表单数据已更新", formData.value);
};

// 获取疫苗计划详情
const getVaccinePlanInfo = async () => {
  if (!props.planId) {
    console.log("获取疫苗计划详情 - 无计划ID，跳过获取");
    return;
  }

  console.log("获取疫苗计划详情 - 开始获取计划ID:", props.planId);

  try {
    const response = await followApi.getFollowUpPlanVaccinationInfo({
      planId: props.planId
    });

    if (response?.data) {
      console.log("获取疫苗计划详情 - 数据获取成功", response.data);

      const data = response.data;

      // 将API数据转换为前端展示格式
      const vaccineName = getVaccineNameById(data.vaccineType);
      console.log(
        "获取疫苗计划详情 - 疫苗类型ID:",
        data.vaccineType,
        "疫苗名称:",
        vaccineName
      );

      const vaccineItem: VaccineItem = {
        id: 1,
        vaccineName: vaccineName,
        vaccineType: data.vaccineType,
        currentDose: data.currentDoseNumber || 1,
        totalDoses: data.totalDoses || 3,
        vaccinationDate: String(data.vaccinationDate),
        timeWindowType: data.asap === 2 ? "asap" : "suggested",
        timeWindowRange:
          data.windowStartDate && data.windowEndDate
            ? [String(data.windowStartDate), String(data.windowEndDate)]
            : null,
        contraindicationType: data.precautions ? "custom" : "none",
        contraindicationText: data.precautions || ""
      };

      // 更新疫苗列表
      vaccineList.value = [vaccineItem];

      updateFormData();
      console.log("获取疫苗计划详情 - 疫苗列表已更新");
    }
  } catch (error) {
    console.error("获取疫苗计划详情失败:", error);
    ElMessage.error("获取疫苗计划详情失败");
  }
};

// 根据疫苗类型ID获取疫苗名称
const getVaccineNameById = (vaccineType: number): string => {
  const foundVaccine = vaccineOptions.value.find(
    item => item.id === vaccineType
  );

  return foundVaccine?.name || "";
};

// 提交表单
const submitForm = async () => {
  console.log("提交疫苗计划表单 - 开始验证和提交，模式:", defaultMode.value);

  if (!formRef.value) {
    console.error("提交疫苗计划表单 - 表单引用不存在");
    return;
  }

  try {
    await formRef.value.validate();
    console.log("提交疫苗计划表单 - 表单验证通过");

    updateFormData(); // 确保数据最新

    let response;
    if (isCreateMode.value) {
      // 创建新的疫苗计划
      console.log("疫苗计划 - 创建模式，调用创建接口");
      response = await followApi.getFollowUpPlanVaccinationCreate(
        formData.value
      );
    } else if (isEditMode.value && props.planId) {
      // 编辑现有疫苗计划
      console.log("疫苗计划 - 编辑模式，调用更新接口，计划ID:", props.planId);
      const updateData: VaccinationUpdateFrom = {
        ...formData.value,
        planId: props.planId
      };
      response = await followApi.getFollowUpPlanVaccinationUpdate(updateData);
    } else {
      console.error("疫苗计划 - 无效的操作模式或缺少计划ID");
      ElMessage.error("操作失败，请检查参数");
      return;
    }

    if (response?.data) {
      console.log("提交疫苗计划表单 - 提交成功", response.data);
      ElMessage.success(isCreateMode.value ? "创建成功" : "更新成功");
      emit("submit", formData.value);
    }
  } catch (error) {
    console.error("提交疫苗计划表单失败:", error);
    ElMessage.error("保存失败，请检查表单内容");
  }
};

// 暴露方法给父组件
defineExpose({
  submitForm
});

// 初始化
console.log(
  "疫苗计划组件初始化 - 用户ID:",
  props.userId,
  "计划ID:",
  props.planId
);

if (props.planId && !isCreateMode.value) {
  getVaccinePlanInfo();
} else if (isCreateMode.value) {
  // 创建模式下默认添加一条疫苗记录
  handleAddVaccine();
}

// 监听疫苗列表变化
watch(
  vaccineList,
  () => {
    updateFormData();
  },
  { deep: true }
);
</script>

<style lang="scss" scoped>
.vaccine-plan {
  padding: 20px 0;

  .vaccine-list {
    .vaccine-item {
      border: 1px solid #e4e7ed;
      border-radius: 8px;
      margin-bottom: 16px;
      padding: 16px;
      background: #fafafa;

      &:last-child {
        margin-bottom: 0;
      }

      .vaccine-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;
        padding-bottom: 12px;
        border-bottom: 1px solid #e4e7ed;

        .vaccine-title {
          display: flex;
          align-items: center;
          gap: 12px;

          .vaccine-name {
            font-size: 16px;
            font-weight: 600;
            color: #303133;
          }

          .dose-info {
            font-size: 14px;
            color: #606266;
            background: #ecf5ff;
            padding: 4px 8px;
            border-radius: 4px;
          }
        }
      }

      .vaccine-details {
        .form-row {
          display: flex;
          align-items: flex-start;
          margin-bottom: 16px;

          &:last-child {
            margin-bottom: 0;
          }

          .form-label {
            width: 120px;
            font-size: 14px;
            color: #606266;
            line-height: 32px;
            flex-shrink: 0;
          }

          .form-content {
            flex: 1;
            display: flex;
            align-items: center;
            gap: 8px;

            .dose-separator {
              color: #909399;
              font-size: 16px;
              margin: 0 8px;
            }

            .radio-text {
              margin-left: 4px;
            }
          }
        }
      }
    }
  }

  .add-button {
    margin-top: 20px;
    text-align: center;
  }

  :deep(.el-form-item__label) {
    font-weight: normal;
    color: #606266;
  }

  :deep(.el-input__wrapper),
  :deep(.el-textarea__inner) {
    box-shadow: none;
    border: 1px solid #dcdfe6;

    &:hover,
    &:focus {
      border-color: #409eff;
    }
  }

  :deep(.el-select) {
    width: 100%;
  }

  :deep(.el-radio) {
    margin-right: 16px;

    &:last-child {
      margin-right: 0;
    }
  }
}
</style>
